using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TXLooker.Common;
using TXLooker.WorkItemExtention.Core;
using TXLooker.WorkItemExtention.Properties;

namespace TXLooker.WorkItemExtention.UI.QueryManager
{
    public partial class QueryManagerControl : UserControl
    {
        #region Private Fields
        private IOlWorkItemProcessor m_olProccessor;
        private string m_Select;//           = "SELECT [System.Id], [System.WorkItemType], [System.AssignedTo], [System.CreatedBy], [Microsoft.VSTS.Common.Priority], [System.Title], [System.Description]";
        private string m_From = "FROM WorkItems";
        private string m_OrderBy = "ORDER BY [System.Id]";

        private ComboBox m_comboAndOr = new ComboBox();
        private ComboBox m_comboField = new ComboBox();
        private ComboBox m_comboOperator = new ComboBox();
        private ComboBox m_comboValue = new ComboBox();
        private ComboBoxTree m_comboTreeValue = new ComboBoxTree();

        private string m_storedString;

        private SolidBrush m_SysBack = new SolidBrush(SystemColors.Highlight);

        private Dictionary<string, string[]> m_operatorsDictionary = new Dictionary<string, string[]>();
        private Dictionary<string, FieldDefinition> m_fieldDictionary = new Dictionary<string, FieldDefinition>();

        private string m_queryString;
        private bool m_bAllowSave;

        private List<Group> m_groupCollection = new List<Group>();
        private int m_distancePixel = 0;

        private Point m_pointLastCell = new Point(-1, -1);
        private bool m_allowePaint = false;

        private int m_rowNewValue;

        private List<int> m_columnsWidthResulGrid = new List<int>();

        private IQueryManagerProcessor m_QueryManagerProcessor;
        private TabPage m_currentTab;
        private TabControl m_tabControl;
        private bool m_newQuery;
        #endregion

        #region Events & raise methods

        public event EventHandler UpdateQuery;
        public event SavedQueryEventHandler SavedQuery;
        public event AllowSaveQueryEventHandler AllowSaveQuery;

        public delegate void SavedQueryEventHandler(object sender,SavedQueryEventArgs e);
        public delegate void AllowSaveQueryEventHandler(object sender,AllowSaveQueryEventArgs e);

        private void RaiseAllowSaveQueryEventArgs(StoredQuery query,string queryText, bool newQuery)
        {
            if (this.AllowSaveQuery != null)
                this.AllowSaveQuery(this,new AllowSaveQueryEventArgs(query,queryText,newQuery));
        }

        private void RaiseSavedQuery(StoredQuery query, WIObject wiObject)
        {
            if (this.SavedQuery != null)
                this.SavedQuery(this,new SavedQueryEventArgs(query,wiObject));
        }

        private void RaiseUpdateQueryEvent()
        {
            if (UpdateQuery != null)
                this.UpdateQuery(this, EventArgs.Empty);
        }

        #endregion

        #region Initialize Methods

        private void InitOperatorsDictionary()
        {
            string[] intOperators = new string[] { ConstantOperators.Equal, ConstantOperators.NotEqual, ConstantOperators.Atomic, ConstantOperators.Major, ConstantOperators.AtomicEqual, ConstantOperators.MajorEqual, ConstantOperators.In };
            string[] dateTimeOperators = intOperators;
            string[] stringOperators = new string[] { ConstantOperators.Equal, ConstantOperators.NotEqual, ConstantOperators.Atomic, ConstantOperators.Major, ConstantOperators.AtomicEqual, ConstantOperators.MajorEqual, ConstantOperators.In, ConstantOperators.Contains, ConstantOperators.Does_Not_Contain, ConstantOperators.Was_Ever };
            string[] plainTextOperators = new string[] { ConstantOperators.Contains, ConstantOperators.Does_Not_Contain };
            string[] historyOperators = plainTextOperators;
            string[] treePathOperators = new string[] { ConstantOperators.Under, ConstantOperators.Not_Under, ConstantOperators.Equal, ConstantOperators.NotEqual, ConstantOperators.In };
            string[] doubleOperators = new string[] { ConstantOperators.Equal, ConstantOperators.NotEqual, ConstantOperators.Atomic, ConstantOperators.Major, ConstantOperators.AtomicEqual, ConstantOperators.MajorEqual, ConstantOperators.In, ConstantOperators.Was_Ever };
            string[] htmlOperators = plainTextOperators;
            string[] projectOperators = new string[] { ConstantOperators.Equal, ConstantOperators.NotEqual, ConstantOperators.In };

            m_operatorsDictionary.Add(ConstantFieldType.Integer, intOperators);
            m_operatorsDictionary.Add(ConstantFieldType.DateTime, dateTimeOperators);
            m_operatorsDictionary.Add(ConstantFieldType.String, stringOperators);
            m_operatorsDictionary.Add(ConstantFieldType.PlainText, plainTextOperators);
            m_operatorsDictionary.Add(ConstantFieldType.History, historyOperators);
            m_operatorsDictionary.Add(ConstantFieldType.TreePath, treePathOperators);
            m_operatorsDictionary.Add(ConstantFieldType.Double, doubleOperators);
            m_operatorsDictionary.Add(ConstantFieldType.Html, htmlOperators);
            m_operatorsDictionary.Add(ConstantFieldType.Team_Project, projectOperators);
        }


        void EnableCombobBoxes(bool bEnable)
        {
            m_comboAndOr.Visible = bEnable;
            m_comboField.Visible = bEnable;
            m_comboOperator.Visible = bEnable;
            m_comboValue.Visible = bEnable;
            m_comboTreeValue.Visible = bEnable;
        }

        void InitComboBoxes()
        {
            EnableCombobBoxes(false);

            m_comboAndOr.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            m_comboField.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            m_comboOperator.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            m_comboValue.AutoCompleteMode = AutoCompleteMode.SuggestAppend;

            this.m_comboAndOr.Name = Enum.GetName(typeof(ComboboxName), ComboboxName.And_Or);
            this.m_comboField.Name = Enum.GetName(typeof(ComboboxName), ComboboxName.Field);
            this.m_comboOperator.Name = Enum.GetName(typeof(ComboboxName), ComboboxName.Operator);
            this.m_comboValue.Name = Enum.GetName(typeof(ComboboxName), ComboboxName.Value);

            m_comboAndOr.DropDownStyle = ComboBoxStyle.DropDownList;
            m_comboField.DropDownStyle = ComboBoxStyle.DropDownList;
            m_comboOperator.DropDownStyle = ComboBoxStyle.DropDownList;
            m_comboValue.DropDownStyle = ComboBoxStyle.DropDown;

            m_comboTreeValue.TreeView.Height = 300;
            m_comboTreeValue.BranchSeparator = @"\";

            //Events
            m_comboAndOr.SelectedValueChanged += new EventHandler(OnAndOrTextChanged);
            m_comboField.SelectedValueChanged += new EventHandler(OnFieldTextChanged);
            m_comboOperator.SelectedValueChanged += new EventHandler(OnOperatorTextChanged);
            m_comboOperator.DropDown += new EventHandler(OnOperatorDropDown);
            m_comboValue.TextChanged += new EventHandler(OnValueTextChanged);
            m_comboValue.DropDown += new EventHandler(OnValueDropDown);
            //m_comboTreeValue.TreeView.BeforeSelect += new TreeViewCancelEventHandler(OnValueBeforeSelect);

            this.Controls.Add(m_comboValue);
            this.Controls.Add(m_comboOperator);
            this.Controls.Add(m_comboField);
            this.Controls.Add(m_comboAndOr);
            this.Controls.Add(m_comboTreeValue);

            m_comboAndOr.Items.AddRange(new string[] { ConstantAndOr.And, ConstantAndOr.Or });
        }

        private void InitInterationPath(WorkItemStore store)
        {
            this.m_comboTreeValue.TreeView.Nodes.Clear();
            foreach (Project project in store.Projects)
            {
                foreach (Node node in project.IterationRootNodes)
                {
                    m_comboTreeValue.TreeView.Nodes.Add(NodeToTreeNode(node));
                }
            }
        }

        private void InitAreaPath(WorkItemStore store)
        {
            this.m_comboTreeValue.TreeView.Nodes.Clear();
            foreach (Project project in store.Projects)
            {
                foreach (Node node in project.AreaRootNodes)
                {
                    m_comboTreeValue.TreeView.Nodes.Add(NodeToTreeNode(node));
                }
            }
        }

        private int SortByName(string s1, string s2)
        {
            return s1.CompareTo(s2);
        }

        TreeNode NodeToTreeNode(Node node)
        {
            TreeNode treeNode = new TreeNode(node.Name);

            foreach (Node child in node.ChildNodes)
            {
                treeNode.Nodes.Add(NodeToTreeNode(child));
            }

            return treeNode;
        }

        private void ComboBoxStart(ComboBox comboBox)
        {
            int comboTop = CellTop - (this.m_rowNewValue * this.m_queryGrid.Rows[0].Height);
            comboBox.Visible = false;
            m_comboAndOr.Width = 0;
            comboBox.Left = CellLeft;
            comboBox.Top = comboTop;
            comboBox.Width = CellWidth;    
            comboBox.BringToFront();
            comboBox.Text = m_queryGrid.CurrentCell.Value + "";
            comboBox.Visible = true;
            comboBox.Focus();
        }

        private void InitTreePath(string path)
        {
            switch (path)
            {
                case ConstantFieldType.Iteration_Path:
                    InitInterationPath(this.QueryManagerProcessor.Store);
                    break;
                case ConstantFieldType.Area_Path:
                    InitAreaPath(this.QueryManagerProcessor.Store);
                    break;
                default: break;
            }

            m_comboTreeValue.Visible = false;
            m_comboTreeValue.Width = 0;

            m_comboTreeValue.Left = CellLeft;
            m_comboTreeValue.Top = CellTop;
            m_comboTreeValue.Width = CellWidth;
            m_comboTreeValue.BringToFront();
            m_comboTreeValue.Text = m_queryGrid.CurrentCell.Value + "";
            m_comboTreeValue.Visible = true;
            m_comboTreeValue.Focus();

        }

        private void DisableComboBoxes()
        {
            m_comboAndOr.Visible = false;
            m_comboAndOr.Width = 0;

            m_comboField.Visible = false;
            m_comboField.Width = 0;

            m_comboOperator.Visible = false;
            m_comboOperator.Width = 0;

            m_comboValue.Visible = false;
            m_comboValue.Width = 0;

            m_comboTreeValue.Visible = false;
            m_comboTreeValue.Width = 0;
        }

        private void FillFieldComboBox(WorkItemStore store)
        {
            m_comboField.Items.Clear();
            m_fieldDictionary.Clear();
            FieldDefinitionCollection fieldDefinationCollection = store.FieldDefinitions;
            List<string> fieldNames = new List<string>();
            foreach (FieldDefinition field in fieldDefinationCollection)
            {
                fieldNames.Add(field.Name);
                m_fieldDictionary.Add(field.Name, field);
            }
            fieldNames.Sort(SortByName);
            foreach (string s in fieldNames)
            {
                m_comboField.Items.Add(s);
            }
        }

        #endregion

        private QueryManagerControl()
        {
            InitializeComponent();
        }

        private QueryManagerControl(IQueryManagerProcessor queryManagerProcessor) : this()
        {
            this.QueryManagerProcessor = queryManagerProcessor;
        }

        public QueryManagerControl(IQueryManagerProcessor queryManagerProcessor, IOlWorkItemProcessor olWorkItemProcessor,TabPage currentTab,TabControl tabConrol,bool newQuery)
            : this(queryManagerProcessor)
        {
            this.OlWorkItemProcessor = olWorkItemProcessor;
            this.m_currentTab = currentTab;
            this.TabControl = tabConrol;
            this.m_newQuery = newQuery;
            this.OnLoad();
        }

        private void OnLoad()
        {
            InitComboBoxes();
            this.FillFieldComboBox(this.QueryManagerProcessor.Store);  
            if (!this.m_newQuery)
            {          
                QueryParseManager queryBuilder = new QueryParseManager(this.QueryManagerProcessor.Query.QueryText, this.QueryManagerProcessor.Store);
                this.m_groupCollection = queryBuilder.GroupCollection;

                foreach (QueryParameters param in queryBuilder.QueryList)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    m_queryGrid.Rows.Add("", param.AndOr, param.Field, param.Operator, param.Value);
                }
                this.m_storedString = BuildQuery(false);
            }
            else
            {
                this.m_runQuery.Enabled = false;
                //DataGridViewRow clause = new DataGridViewRow("","",this.m_fieldDictionary[ConstantFields.System_TeamProject].Name,ConstantOperators.Equal,ConstantFields.project);
                //this.m_queryGrid.Rows.Add(clause);
                string field = this.m_fieldDictionary["Team Project"].Name; 
                m_queryGrid.Rows.Add("", "", field, ConstantOperators.Equal, ConstantFields.project);
            }
            InitOperatorsDictionary();
            this.AddSimpleRow();
            this.m_queryGrid[1, 0].ReadOnly = true;
            this.m_queryGrid.Invalidate();  
            this.m_saveQuery.Enabled = false;
        }

        void AddSimpleRow()
        {
            DataGridViewRow newClause = new DataGridViewRow();
            m_queryGrid.Rows.Add(newClause);
            m_allowePaint = true;
        }


        #region Properties

        private TabControl TabControl
        {
            get { return this.m_tabControl; }
            set { this.m_tabControl = value; }
        }

        private TabPage CurrentTab
        {
            get { return this.m_currentTab; }
            set { this.m_currentTab = value; }
        }

        private int LastSelectedRowIndex
        {
            get { return m_queryGrid.SelectedRows[0].Index; }
        }
        private int FirstSelectedRowIndex
        {
            get { return m_queryGrid.SelectedRows[m_queryGrid.SelectedRows.Count - 1].Index; }
        }

        public IOlWorkItemProcessor OlWorkItemProcessor
        {
            get { return this.m_olProccessor; }
            protected set
            {
                if (object.ReferenceEquals(null, value))
                    throw new NullReferenceException();
                this.m_olProccessor = value;
            }
        }

        public IQueryManagerProcessor QueryManagerProcessor
        {
            get { return this.m_QueryManagerProcessor; }
            set
            {
                if (object.ReferenceEquals(value, null))
                    throw new NullReferenceException();
                this.m_QueryManagerProcessor = value;
            }
        }

        private int CellLeft
        {
            get
            {
                int width = m_queryGrid.Location.X /*+ m_gbQueryBody.Location.X*/;
                if (m_queryGrid.CurrentCell.ColumnIndex != 0)
                {
                    for (int i = 0; i < m_queryGrid.CurrentCell.ColumnIndex; i++)
                    {
                        width += m_queryGrid.Columns[i].Width;
                    }
                }
                return width += m_queryGrid.RowHeadersWidth;
            }
        }

        private int CellTop
        {
            get
            {
                int height = m_queryGrid.Location.Y /*+ m_gbQueryBody.Location.Y*/;
                if (m_queryGrid.CurrentCell.RowIndex != 0)
                {
                    for (int i = 0; i < m_queryGrid.CurrentCell.RowIndex; i++)
                    {
                        height += m_queryGrid.Rows[i].Height;
                    }
                }
                return height += m_queryGrid.ColumnHeadersHeight;
            }
        }

        private int CellWidth
        {
            get
            {
                int width = 0;
                width = m_queryGrid.Columns[m_queryGrid.CurrentCell.ColumnIndex].Width;
                return width;
            }
        }

        #endregion

        private void OnScroll(object sender, ScrollEventArgs e)
        {
            this.DisableComboBoxes();
            this.m_queryGrid.Focus();
            this.m_queryGrid.Invalidate();
            this.m_rowNewValue = e.NewValue;
        }

        private void OnEditControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            DisableComboBoxes();
            int lastRow = m_queryGrid.Rows.GetLastRow(DataGridViewElementStates.None);
            if (lastRow == m_queryGrid.CurrentCell.RowIndex)
            {
                if (lastRow != 0)
                {
                    this.m_queryGrid[(int)Columns.AndOr, this.m_queryGrid.CurrentCell.RowIndex].Value = ConstantAndOr.And;
                    this.m_queryGrid[(int)Columns.Operator, this.m_queryGrid.CurrentCell.RowIndex].Value = ConstantOperators.Equal;
                }
                else
                {
                    this.m_queryGrid[(int)Columns.Operator, this.m_queryGrid.CurrentCell.RowIndex].Value = ConstantOperators.Equal;
                }
                this.AddSimpleRow();
            }

            m_queryGrid.SendToBack();
            switch (m_queryGrid.CurrentCell.ColumnIndex)
            {
                case (int)Columns.AndOr:
                    if (m_queryGrid.CurrentCell.RowIndex == 0 && m_queryGrid.CurrentCell.ColumnIndex == 1)
                        break;
                    ComboBoxStart(m_comboAndOr);
                    break;
                case (int)Columns.Filed:
                    ComboBoxStart(m_comboField);
                    break;
                case (int)Columns.Operator:
                    ComboBoxStart(m_comboOperator);
                    break;
                case (int)Columns.Value:
                    if ((string)m_queryGrid[m_queryGrid.CurrentCell.ColumnIndex - 2, m_queryGrid.CurrentCell.RowIndex].Value == ConstantFieldType.Area_Path)
                        InitTreePath(ConstantFieldType.Area_Path);
                    else if ((string)m_queryGrid[m_queryGrid.CurrentCell.ColumnIndex - 2, m_queryGrid.CurrentCell.RowIndex].Value == ConstantFieldType.Iteration_Path)
                        InitTreePath(ConstantFieldType.Iteration_Path);
                    else
                        ComboBoxStart(m_comboValue);
                    break;
                default: break;
            }
        }

        private void OnPaint(object sender, PaintEventArgs e)
        {
            int scrollBarWidth = 0;
            if (this.m_queryGrid.DisplayRectangle.Width < this.m_queryGrid.ClientRectangle.Width)
                scrollBarWidth = this.m_queryGrid.ClientRectangle.Width - this.m_queryGrid.DisplayRectangle.Width;

            try
            {
                switch (m_queryGrid.CurrentCell.ColumnIndex)
                {
                    case (int)Columns.AndOr:
                        m_comboAndOr.Width = CellWidth;
                        break;
                    case (int)Columns.Filed:
                        m_comboField.Width = CellWidth;
                        break;
                    case (int)Columns.Operator:
                        m_comboOperator.Width = CellWidth;
                        break;
                    case (int)Columns.Value:
                        m_comboValue.Width = CellWidth - scrollBarWidth;
                        m_comboTreeValue.Width = CellWidth - scrollBarWidth;
                        break;
                }
            }
            catch  { }

            foreach (Group group in m_groupCollection)
            {
                Rectangle rect1 = m_queryGrid.GetCellDisplayRectangle((int)Columns.GroupRectangle, group.FirstRow, true);
                Rectangle rect2 = m_queryGrid.GetCellDisplayRectangle((int)Columns.GroupRectangle, group.LastRow, true);

                using (Pen p = new Pen(Color.Black))
                {
                    if (rect1.Left < rect2.Left)
                    {
                        Rectangle rect3 = m_queryGrid.GetCellDisplayRectangle((int)Columns.GroupRectangle, m_queryGrid.FirstDisplayedScrollingRowIndex, true);
                        e.Graphics.DrawLine(p, rect2.Left + rect2.Width / 2 - group.Distance, rect2.Top + rect2.Height / 2, rect2.Right, rect2.Top + rect2.Height / 2);
                        e.Graphics.DrawLine(p, rect2.Left + rect2.Width / 2 - group.Distance, rect2.Top + rect2.Height / 2, rect2.Left + rect2.Width / 2 - group.Distance, rect3.Top);
                    }
                    else if (rect1.Left > rect2.Left)
                    {
                        e.Graphics.DrawLine(p, rect1.Left + rect1.Width / 2 - group.Distance, rect1.Top + rect1.Height / 2, rect1.Right, rect1.Top + rect1.Height / 2);
                        e.Graphics.DrawLine(p, rect1.Left + rect1.Width / 2 - group.Distance, rect1.Top + rect1.Height / 2, rect1.Left + rect1.Width / 2 - group.Distance, m_queryGrid.Bottom);
                    }
                    else
                    {
                        e.Graphics.DrawLine(p, rect1.Left + rect1.Width / 2 - group.Distance, rect1.Top + rect1.Height / 2, rect1.Right, rect1.Top + rect1.Height / 2);
                        e.Graphics.DrawLine(p, rect2.Left + rect2.Width / 2 - group.Distance, rect2.Top + rect2.Height / 2, rect2.Right, rect2.Top + rect2.Height / 2);
                        e.Graphics.DrawLine(p, rect1.Left + rect1.Width / 2 - group.Distance, rect1.Top + rect1.Height / 2, rect2.Left + rect2.Width / 2 - group.Distance, rect2.Top + rect2.Height / 2);
                    }
                }
            }
            if (m_allowePaint && this.m_queryGrid.Rows[this.m_queryGrid.Rows.GetLastRow(DataGridViewElementStates.None)].Displayed)
            {
                e.Graphics.DrawString(Resources.CLICK_HERE_TO_ADD_A_CLAUSE, new Font("Arial", 8), Brushes.Black, m_pointLastCell);
            }
        }

        void OnAndOrTextChanged(object sender, EventArgs e)
        {
            if (m_queryGrid.CurrentCell.ColumnIndex == (int)Columns.AndOr)
            {
                if (!m_comboAndOr.Text.Equals(string.Empty))
                    m_queryGrid.CurrentCell.Value = m_comboAndOr.Text;
            }

            AllowSave();
        }

        void OnOperatorDropDown(object sender, EventArgs e)
        {
            if (this.QueryManagerProcessor.Store == null)
                return;
            try
            {
                string fieldValue = (string)m_queryGrid[m_queryGrid.CurrentCell.ColumnIndex - 1, m_queryGrid.CurrentCell.RowIndex].Value;
                if (fieldValue == null || fieldValue.Equals(string.Empty) || fieldValue.Equals(" "))
                    return;

          
                m_comboOperator.Items.Clear();
                FieldDefinition field = m_fieldDictionary[(string)m_queryGrid[m_queryGrid.CurrentCell.ColumnIndex - 1, m_queryGrid.CurrentCell.RowIndex].Value];

                string[] operators = null;
                if (fieldValue == ConstantFieldType.Team_Project)
                    operators = m_operatorsDictionary[ConstantFieldType.Team_Project];
                else
                    operators = m_operatorsDictionary[field.FieldType.ToString()];


                if (operators != null)
                {
                    foreach (string str in operators)
                    {
                        m_comboOperator.Items.Add(str);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteMessageToCustomLog("Error in OnOperatorDropDown " + ex.ToString());
            }
        }

        void OnValueTextChanged(object sender, EventArgs e)
        {
            if (m_queryGrid.CurrentCell.ColumnIndex == (int)Columns.Value)
            {
                //if (!m_comboValue.Text.Equals(string.Empty))
                m_queryGrid.CurrentCell.Value = m_comboValue.Text;
            }
            AllowSave();
        }

        void OnOperatorTextChanged(object sender, EventArgs e)
        {
            if (m_queryGrid.CurrentCell.ColumnIndex == (int)Columns.Operator)
            {
                if (!m_comboOperator.Text.Equals(string.Empty))
                    m_queryGrid.CurrentCell.Value = m_comboOperator.Text;
            }
            AllowSave();
        }

        void OnFieldTextChanged(object sender, EventArgs e)
        {
            if (m_queryGrid.CurrentCell.ColumnIndex == (int)Columns.Filed)
            {
                string selectedText = m_comboField.Text;
                if (!m_comboField.Text.Equals(string.Empty))
                {
                    m_queryGrid.CurrentCell.Value = m_comboField.Text;
                    if (m_queryGrid.CurrentCell.RowIndex == m_queryGrid.Rows.GetLastRow(DataGridViewElementStates.None))
                        this.AddSimpleRow();
                }
            }
            AllowSave();
            //m_queryGrid[(int)Columns.Operator, m_queryGrid.CurrentCell.RowIndex].Value = string.Empty;
            //m_queryGrid[(int)Columns.Value, m_queryGrid.CurrentCell.RowIndex].Value = string.Empty;
        }

        private void AllowSave()
        {
            //if (!m_bAllowSave)
            //{
            //    string newStringQuery = BuildQuery(false);
            //    if (m_storedString == newStringQuery)
            //        this.m_bAllowSave = false;
            //    else
            //    {
            //        this.m_bAllowSave = true;
            //        this.m_saveQuery.Enabled = m_bAllowSave;
            //    }
            //    this.m_queryGrid.Focus();
            //}
            //else 
            //if (this.m_newQuery)
                this.m_saveQuery.Enabled = true;
            RaiseAllowSaveQueryEventArgs(this.QueryManagerProcessor.Query, BuildQuery(false), this.m_newQuery);
        }

        void OnValueDropDown(object sender, EventArgs e)
        {
            if (this.QueryManagerProcessor.Store == null)
                return;
            m_comboValue.Items.Clear();

            string fieldValue = (string)m_queryGrid[m_queryGrid.CurrentCell.ColumnIndex - 2, m_queryGrid.CurrentCell.RowIndex].Value;
            if (fieldValue == null)
                return;
            if (fieldValue.Equals(string.Empty) && fieldValue.Equals(" "))
                return;

            Cursor cur = this.Cursor;

            try
            {
                this.Cursor = Cursors.WaitCursor;
                FieldDefinition field = m_fieldDictionary[m_queryGrid[m_queryGrid.CurrentCell.ColumnIndex - 2, m_queryGrid.CurrentCell.RowIndex].Value as string];
                AllowedValuesCollection collection = field.AllowedValues;

                foreach (string s in collection)
                {
                    m_comboValue.Items.Add(s);
                }

                if (field.ReferenceName.Equals(ConstantFields.System_TeamProject))
                    m_comboValue.Items.AddRange(new string[] { ConstantFields.project });
                if (field.ReferenceName.Equals(ConstantFields.System_AssignedTo))
                    m_comboValue.Items.AddRange(new string[] { ConstantValues.me });
                if (field.FieldType.ToString() == ConstantFieldType.DateTime)
                    m_comboValue.Items.AddRange(new string[] { ConstantValues.Today, ConstantValues.Today_1, ConstantValues.Today_7, ConstantValues.Today_30 });
            }
            catch (System.Exception ex)
            {
                LogManager.WriteMessageToCustomLog("Error in OnValueDropDown " + ex.ToString());
            }
            finally
            {
                this.Cursor = cur;
            }

        }

        #region Build Query 

        private void GetSelectedColumns()
        {
            WIStoredQuery storedQuery = this.QueryManagerProcessor.SelectedObject as WIStoredQuery;
            if (storedQuery == null)
                return;
            WorkItemCollection workitems = storedQuery.ExecQuery();

            //if (workitems == null || (workitems != null && workitems.Count == 0)) return;

            //init view
            if (storedQuery.FolderView == null)
                storedQuery.FolderView = new OlWIQueryFolderView(workitems);

            OlWIQueryFolderView wiView = storedQuery.FolderView as OlWIQueryFolderView;

            m_Select = string.Empty;
            m_Select += ConstantKeyWords.SELECT + " ";
            List<OlWIQueryColumn> selectedColumns = new List<OlWIQueryColumn>();
            this.m_columnsWidthResulGrid.Clear();
            foreach (OlWIQueryColumn column in wiView.Columns)
            {
                selectedColumns.Add(column);
                this.m_columnsWidthResulGrid.Add(column.Width);
            }

            for (int i = 0; i < selectedColumns.Count; i++)
            {
                if (i == selectedColumns.Count - 1)
                    this.m_Select += "[" + this.m_fieldDictionary[selectedColumns[i].Caption].ReferenceName + "] ";
                else
                    this.m_Select += "[" + this.m_fieldDictionary[selectedColumns[i].Caption].ReferenceName + "], ";
            }
        }

        private string BuildQuery(bool emptyRows)
        {
            //if (emptyRows)
            //    ClearEmptyRows();

            string buildString;
            if (!this.m_newQuery)
                this.GetSelectedColumns();
            DisableComboBoxes();
            buildString = string.Empty;
            buildString = string.Format("{0} {1} {2} ", m_Select, m_From, ConstantKeyWords.WHERE);
            //this.RaiseDeleteNonFilledClauses();


            List<int> firstGroupIndexes = new List<int>();
            List<int> lastGroupIndexes = new List<int>();

            foreach (Group group in m_groupCollection)
            {
                firstGroupIndexes.Add(group.FirstRow);
                lastGroupIndexes.Add(group.LastRow);
            }

            string strOperator = string.Empty;
            for (int i = 0; i < m_queryGrid.Rows.Count; i++)
            {
                for (int j = 1; j < m_queryGrid.Columns.Count; j++)
                {
                    if (m_queryGrid.Columns[(int)Columns.AndOr] == m_queryGrid.Columns[j])
                        BuildAndOr(i, j,ref buildString);
                    else if (m_queryGrid.Columns[(int)Columns.Filed] == m_queryGrid.Columns[j])
                        BuildField(firstGroupIndexes, i, j,ref buildString);
                    else if (m_queryGrid.Columns[(int)Columns.Operator] == m_queryGrid.Columns[j])
                        strOperator = BuildOperator(i, j,ref buildString);
                    else if (m_queryGrid.Columns[(int)Columns.Value] == m_queryGrid.Columns[j])
                        BuildValue(lastGroupIndexes, i, j, strOperator,ref buildString);
                }
            }
            buildString += m_OrderBy;
            Debug.WriteLine("Query:\t" + buildString);
            this.m_queryGrid.Focus();
            return buildString;
        }

        private void ClearEmptyRows()
        {
            //try
            //{
            //    int rowsCount = this.m_queryGrid.Rows.Count;
            //    List<int> rowIndexesToDelete = new List<int>();
            //    List<Group> groupsToDelete = new List<Group>();
            //    foreach (DataGridViewRow row in this.m_queryGrid.Rows)
            //    {
            //        string andOrColumnValue = (string)this.m_queryGrid[(int)Columns.AndOr, row.Index].Value;
            //        string fieldColumnValue = (string)this.m_queryGrid[(int)Columns.Filed, row.Index].Value;
                     
            //        if ((andOrColumnValue != null || andOrColumnValue != string.Empty) && (fieldColumnValue == null || fieldColumnValue == string.Empty))
            //        {
            //             foreach (Group group in this.m_groupCollection)
            //             {
            //                 if (group.FirstRow > row.Index && group.LastRow < row.Index)
            //                     groupsToDelete.Add(group);
            //             }
            //             rowIndexesToDelete.Add(row.Index);
            //         }
            //    }
            //    //for (int i = 0; i < rowsCount; i++)
            //    //{
            //    //    string andOrColumnValue = (string)this.m_queryGrid[(int)Columns.AndOr, i].Value;
            //    //    string fieldColumnValue = (string)this.m_queryGrid[(int)Columns.Filed, i].Value;
            //    //    if ((andOrColumnValue != null || andOrColumnValue != string.Empty) && (fieldColumnValue == null || fieldColumnValue == string.Empty))
            //    //    {
            //    //        foreach (Group group in this.m_groupCollection)
            //    //        {
            //    //            if (group.FirstRow > i && group.LastRow < i)
            //    //                groupsToDelete.Add(group);
            //    //        }
            //    //        rowIndexesToDelete.Add(i);
            //    //    }
            //    //}

            //    foreach (int i in rowIndexesToDelete)
            //        this.m_queryGrid.Rows.RemoveAt(i);
            //    foreach (Group group in groupsToDelete)
            //        this.m_groupCollection.Remove(group);
            //}
            //catch (Exception ex)
            //{ 
            
            //}
        }

        private void BuildAndOr(int i, int j, ref string buildString)
        {
            if (m_queryGrid[j, i].Value != null)
            {
                string strAndOr = m_queryGrid[j, i].Value as string;
                buildString += strAndOr.ToUpper() + " ";
            }
        }

        private void BuildField(List<int> firstGroupIndexes, int i, int j, ref string buildString)
        {
            if (m_queryGrid[j, i].Value != null)
            {
                int removeTimes = 0;
                foreach (int integer in firstGroupIndexes)
                {
                    if (integer == i)
                    {
                        buildString += ConstantOperators.ForwardBracket + " ";
                        removeTimes++;
                    }
                }

                for (uint ui = 0; ui < removeTimes; ui++)
                    firstGroupIndexes.Remove(i);

                FieldDefinition field = m_fieldDictionary[m_queryGrid[j, i].Value as string];
                buildString += string.Format("[{0}] ", field.ReferenceName);
            }
        }

        private void BuildValue(List<int> lastGroupIndexes, int i, int j, string strOperator, ref string buildString)
        {
            if (m_queryGrid[j, i].Value != null)
            {
                string value = (string)m_queryGrid[j, i].Value;
                if (value.Contains("@"))
                    buildString += string.Format("{0} ", value);
                else if (strOperator == ConstantOperators.In || strOperator == ConstantOperators.IN)
                    buildString += string.Format("('{0}') ", value);
                else
                    buildString += string.Format("'{0}' ", m_queryGrid[j, i].Value);
                int removeTimes = 0;
                foreach (int integer in lastGroupIndexes)
                {
                    if (integer == i)
                    {
                        buildString += " " + ConstantOperators.BackBracket + " ";
                        removeTimes++;
                    }
                }

                for (uint ui = 0; ui < removeTimes; ui++)
                    lastGroupIndexes.Remove(i);
            }
        }

        private void QuerySelected(StoredQuery query)
        {
            QueryParseManager queryBuilder = new QueryParseManager(query.QueryText, this.QueryManagerProcessor.Store);
            this.m_groupCollection = queryBuilder.GroupCollection;

            foreach (QueryParameters param in queryBuilder.QueryList)
            {
                DataGridViewRow row = new DataGridViewRow();
                m_queryGrid.Rows.Add("", param.AndOr, param.Field, param.Operator, param.Value, null);
            }

            this.AddSimpleRow();
            this.m_queryGrid[1, 0].ReadOnly = true;
            this.m_queryGrid.Invalidate();
        }

        private string BuildOperator(int i, int j, ref string buildString)
        {
            string oper = string.Empty;
            if (m_queryGrid[j, i].Value != null || string.Empty != (string)m_queryGrid[j, i].Value)
            {

                switch ((string)m_queryGrid[j, i].Value)
                {
                    case ConstantOperators.In:
                        oper = ConstantOperators.IN;
                        break;
                    case ConstantOperators.Was_Ever:
                        oper = ConstantOperators.EVER;
                        break;
                    case ConstantOperators.Contains:
                        oper = ConstantOperators.CONTAINS;
                        break;
                    case ConstantOperators.Does_Not_Contain:
                        oper = ConstantOperators.NOT_CONTAINS;
                        break;
                    case ConstantOperators.Under:
                        oper = ConstantOperators.UNDER;
                        break;
                    case ConstantOperators.Not_Under:
                        oper = ConstantOperators.NOT_UNDER;
                        break;
                    default: oper = m_queryGrid[j, i].Value + "";
                        break;
                }
                buildString += oper + " ";
            }
            return oper;
        }
        #endregion

        private void OnRunQuery(object sender, EventArgs e)
        {
            m_queryString = BuildQuery(true);

            try
            {
                StringBuilder builder = new StringBuilder(this.m_queryString);
                string projectName = WorkItemExtentionGlobal.GetProject(this.QueryManagerProcessor.SelectedObject).Name;
                builder.Replace(ConstantFields.project, string.Format("'{0}'", projectName));
                this.m_gridQueryResults.LoadFromWiql(this.QueryManagerProcessor.Store, builder.ToString());

               
                //set columns width in m_gridQueryResults
                for (int i = 0; i < m_columnsWidthResulGrid.Count; i++)
                {
                    this.m_gridQueryResults.Columns[i].Width = m_columnsWidthResulGrid[i];
                }
            }
            catch(Exception ex)
            {
                LogManager.WriteMessageToCustomLog("Error in OnRunQuery " + ex.ToString());
            }
        }

        private void OnCellResultGridDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int[] IDs = this.m_gridQueryResults.GetSelectedIds();

            WorkItem workItem = this.m_gridQueryResults.WorkItemCollection.Store.GetWorkItem(IDs[0]);

            WorkItemForm form = new WorkItemForm(workItem, this.OlWorkItemProcessor);
            form.ShowDialog();
        }

        private void OnQueryGridCellPaint(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex == (int)Columns.GroupRectangle && e.RowIndex > -1)
            {
                e.Handled = true;
                if (!m_queryGrid[e.ColumnIndex, e.RowIndex].Selected)
                {
                    e.Graphics.FillRectangle(new SolidBrush(SystemColors.HighlightText), e.CellBounds);
                    e.Graphics.DrawLine(Pens.Silver, e.CellBounds.X + e.CellBounds.Width - 1, e.CellBounds.Y, e.CellBounds.X + e.CellBounds.Width - 1, e.CellBounds.Y + e.CellBounds.Height);

                    //Draw a verticle line to separate the next column
                    Rectangle rect = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height - 1);
                    e.PaintContent(rect);

                    //Draw the last line
                    if (e.RowIndex == m_queryGrid.Rows.Count - 1)
                    {
                        e.Graphics.DrawLine(Pens.Silver, e.CellBounds.X, e.CellBounds.Y + e.CellBounds.Height - 1, e.CellBounds.X + e.CellBounds.Width, e.CellBounds.Y + e.CellBounds.Height - 1);
                    }
                }
                else
                {
                    e.Graphics.FillRectangle(m_SysBack, e.CellBounds);
                    e.PaintContent(e.CellBounds);
                }
            }

            DrawTextLastRow(e);
            if (this.m_allowePaint)
            {
                DrawLastRowWithoutSeparateLines(e);
            }
        }

        private void DrawTextLastRow(DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == m_queryGrid.RowCount - 1 && e.ColumnIndex == (int)Columns.AndOr)
            {
                m_pointLastCell = new Point(e.CellBounds.X + 2, e.CellBounds.Y + 2);
            }
        }

        private void DrawLastRowWithoutSeparateLines(DataGridViewCellPaintingEventArgs e)
        {
            if ((e.RowIndex == m_queryGrid.RowCount - 1) && (e.ColumnIndex > (int)Columns.GroupRectangle))
            {
                e.Handled = true;
                e.Graphics.FillRectangle(new SolidBrush(SystemColors.HighlightText), e.CellBounds);
                e.Graphics.DrawLine(Pens.Silver, e.CellBounds.X, e.CellBounds.Y, e.CellBounds.X + e.CellBounds.Width, e.CellBounds.Y);
                e.Graphics.DrawLine(Pens.Silver, e.CellBounds.X, e.CellBounds.Y + e.CellBounds.Height - 1, e.CellBounds.X + e.CellBounds.Width, e.CellBounds.Y + e.CellBounds.Height - 1);
            }
        }

        private void OnSaveQuery(object sender, EventArgs e)
        {
            if (!this.m_newQuery)
                SaveOldQuery();
            else
                SaveNewQuery();               
        }

        private void SaveNewQuery()
        {
            InitColumnsForm colForm = new InitColumnsForm(this.m_fieldDictionary);
            colForm.ShowDialog();
            this.m_Select = colForm.SelectString;
            if (!colForm.OK)
                return;

            SaveAsQueryForm form = new SaveAsQueryForm(QueryManagerProcessor, BuildQuery(true), Resources.NEW_QUERY);
            form.ShowDialog();
            if (!form.Save)
                return;
            RaiseUpdateQueryEvent();
            RaiseSavedQueryBySaveType(form);
            this.m_currentTab.Text = form.FullQueryName;
            this.m_tabControl.SelectedTab = this.m_currentTab;
            this.m_runQuery.Enabled = true;
            this.m_newQuery = false;
        }

        private void RaiseSavedQueryBySaveType(SaveAsQueryForm form)
        {
            switch (form.SaveType)
            {
                case SaveType.TeamQuery:
                case SaveType.MyQuery:
                    RaiseSavedQuery(form.Query,form.WIObject);
                    break;
                default: break;
            }
        }

        private void SaveOldQuery()
        {
            WIStoredQuery wiQuery = this.QueryManagerProcessor.SelectedObject as WIStoredQuery;
            if (wiQuery == null) return;

            Cursor cursor = this.Cursor;

            try
            {
                this.Cursor = Cursors.WaitCursor;
                StoredQuery query = wiQuery.GetQuery();
                query.QueryText = BuildQuery(true);
                RaiseUpdateQueryEvent();
                RaiseSavedQuery(query,this.QueryManagerProcessor.SelectedObject);
                query.Update();
                this.m_saveQuery.Enabled = false;
                MessageBox.Show(Properties.Resources.STRING_QUERY_HAS_BEEN_UPDATED_SUCCESFULLY, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch(UnauthorizedAccessException ex)
            {
                MessageBox.Show(ex.Message, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception)
            {
                MessageBox.Show(Resources.WRONG_FIELD_DEFINITIONS, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = cursor;
            }
        }

        void OnEndUpdate(object sender, EventArgs e)
        {
            
        }

        private void OnRemoveClauses(object sender, EventArgs e)
        {
            RemoveClauses();
        }

        private void RemoveClauses()
        {
            DisableComboBoxes();
            if (m_groupCollection.Count > 0)
            {
                if (MessageBox.Show(Resources.STRING_EXISTING_CLAUSE_GROUPING_WILL_ALSO_BE_DELETED, this.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    RemoveSelectedRows();
                    m_groupCollection.Clear();
                    m_distancePixel = 0;
                }
            }
            else
                RemoveSelectedRows();
            this.m_rowNewValue = 0;
        }

        private void RemoveSelectedRows()
        {
            foreach (DataGridViewRow row in m_queryGrid.SelectedRows)
                m_queryGrid.Rows.Remove(row);
            if (this.m_queryGrid.Rows.Count == 0)
                this.AddSimpleRow();
            else
            {
                this.m_queryGrid[(int)Columns.AndOr, 0].Value = string.Empty;
                //this.AddSimpleRow();
            }
            this.AllowSave();
        }

        private void OnGoupClauses(object sender, EventArgs e)
        {
            int firstRowSelectedIndex = FirstSelectedRowIndex;
            int lastRowSelectedIndex = LastSelectedRowIndex;

            if (lastRowSelectedIndex < firstRowSelectedIndex)
            {
                CommonGlobal.ReverseVariables(ref firstRowSelectedIndex, ref lastRowSelectedIndex);
            }
            m_groupCollection.Add(new Group(firstRowSelectedIndex, lastRowSelectedIndex, m_distancePixel));
            this.m_queryGrid.Invalidate();
            this.AllowSave();
        }

        private void OnUngroupClauses(object sender, EventArgs e)
        {
            int firstRowSelectedIndex = FirstSelectedRowIndex;
            int lastRowSelectedIndex = LastSelectedRowIndex;

            if (lastRowSelectedIndex < firstRowSelectedIndex)
            {
                CommonGlobal.ReverseVariables(ref firstRowSelectedIndex, ref lastRowSelectedIndex);
            }

            Group groupDelete = null;

            foreach (Group group in m_groupCollection)
            {
                if (group.FirstRow == firstRowSelectedIndex && group.LastRow == lastRowSelectedIndex)
                    groupDelete = group;
                if (group.Distance != 0)
                    m_distancePixel = 0;
            }

            m_groupCollection.Remove(groupDelete);
            this.m_queryGrid.Invalidate();
            this.AllowSave();
        }

        private void OnColumnOptions(object sender, EventArgs e)
        {
            WIQLViewForm form = new WIQLViewForm();
            if (this.QueryManagerProcessor.SelectedObject != null)
                form.GuidNodeExpand = this.QueryManagerProcessor.SelectedObject.Type != WIObjectType.Server ? this.QueryManagerProcessor.SelectedObject.ID : Guid.Empty;
            form.ShowDialog();
        }

        private void OnContextMenuQueryGridOpening(object sender, CancelEventArgs e)
        {
            m_ungroupClausesToolStripMenuItem.Enabled = false;
            m_groupClausesToolStripMenuItem.Enabled = false;

            if (m_queryGrid.SelectedRows.Count >= 2)
            {
                bool bAllowUngroup = false;
                bool bAllowGroup = true;

                int firstRowSelectedIndex = FirstSelectedRowIndex;
                int lastRowSelectedIndex = LastSelectedRowIndex;

                if (lastRowSelectedIndex < firstRowSelectedIndex)
                {
                    CommonGlobal.ReverseVariables(ref firstRowSelectedIndex, ref lastRowSelectedIndex);
                }

                bAllowGroup = CheckToAllowGroup(bAllowGroup, firstRowSelectedIndex, lastRowSelectedIndex);

                CheckToAllowUngroup(ref bAllowUngroup, ref bAllowGroup, firstRowSelectedIndex, lastRowSelectedIndex);

                m_ungroupClausesToolStripMenuItem.Enabled = bAllowUngroup;
                m_groupClausesToolStripMenuItem.Enabled = bAllowGroup;
            }

            //Disable removing last row
            if (this.m_queryGrid.SelectedRows.Count > 1)
            {
                int firstRow = this.m_queryGrid.SelectedRows[0].Index;
                int lastRow = this.m_queryGrid.SelectedRows[this.m_queryGrid.SelectedRows.Count - 1].Index;

                if (lastRow < firstRow)
                    CommonGlobal.ReverseVariables(ref lastRow, ref firstRow);
                if (lastRow == this.m_queryGrid.Rows.GetLastRow(DataGridViewElementStates.None))
                    this.m_removeClausesToolStripMenuItem.Enabled = false;
                else
                    this.m_removeClausesToolStripMenuItem.Enabled = true;
            }
            else if(this.m_queryGrid.SelectedRows.Count == 1)
            {
                if (this.m_queryGrid.Rows.GetLastRow(DataGridViewElementStates.None) == this.m_queryGrid.SelectedRows[0].Index)
                    this.m_removeClausesToolStripMenuItem.Enabled = false;
                else
                    this.m_removeClausesToolStripMenuItem.Enabled = true;
            }
        }

        private void CheckToAllowUngroup(ref bool bAllowUngroup, ref bool bAllowGroup, int firstRowSelectedIndex, int lastRowSelectedIndex)
        {
            //check to allow ungroup
            foreach (Group group in m_groupCollection)
            {
                if (group.FirstRow == firstRowSelectedIndex && group.LastRow == lastRowSelectedIndex)
                {
                    bAllowUngroup = true;
                    bAllowGroup = false;
                }
            }
        }

        private bool CheckToAllowGroup(bool bAllowGroup, int firstRowSelectedIndex, int lastRowSelectedIndex)
        {
            //check to allow group
            foreach (Group group in m_groupCollection)
            {
                if (!((lastRowSelectedIndex >= group.FirstRow) && (group.LastRow >= firstRowSelectedIndex)))
                {
                    bAllowGroup = true;
                }
                else
                {
                    bAllowGroup = false;
                    if (group.FirstRow == firstRowSelectedIndex && group.LastRow < lastRowSelectedIndex)
                    {
                        bAllowGroup = true;
                        m_distancePixel += 3;
                        break;
                    }
                    else if (group.LastRow == lastRowSelectedIndex && group.FirstRow > firstRowSelectedIndex)
                    {
                        bAllowGroup = true;
                        m_distancePixel += 3;
                        break;
                    }
                    else if (group.LastRow < lastRowSelectedIndex && group.FirstRow > firstRowSelectedIndex)
                    {
                        bAllowGroup = true;
                        m_distancePixel += 3;
                    }
                    else
                    {
                        bAllowGroup = false;
                        break;
                    }
                }
            }
            if (lastRowSelectedIndex == this.m_queryGrid.Rows.GetLastRow(DataGridViewElementStates.None))
                bAllowGroup = false;
            return bAllowGroup;
        }

        private void OnSaveAsQuery(object sender, EventArgs e)
        {
            if (!this.m_newQuery)
            {
                SaveAsQueryForm form = new SaveAsQueryForm(this.QueryManagerProcessor, BuildQuery(true), this.QueryManagerProcessor.Query.Name);
                form.ShowDialog();
                if (!form.Save)
                    return;
                RaiseUpdateQueryEvent();
                RaiseSavedQueryBySaveType(form);
            }
            else
                SaveNewQuery();
        }

        private void OnClose(object sender, EventArgs e)
        {
            if (m_bAllowSave)
            {
                if (MessageBox.Show(Resources.STRING_DO_YOU_WISH_TO_SAVE_THE_CHANGES, Resources.UI_QUERY_MANAGER_CAPTION, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    switch (m_newQuery)
                    {
                        case false:
                            this.SaveOldQuery();
                            break;
                        case true:
                            this.SaveNewQuery();
                            break;
                    }
                }
            }
            this.TabControl.TabPages.Remove(this.CurrentTab);
        }

        private void OnQueryManagerControlSizeChanged(object sender, EventArgs e)
        {
            this.m_queryGrid.Columns[(int)Columns.Value].Width = m_queryGrid.Width -
                (this.m_queryGrid.Columns[(int)Columns.AndOr].Width +
                this.m_queryGrid.Columns[(int)Columns.Filed].Width +
                this.m_queryGrid.Columns[(int)Columns.GroupRectangle].Width +
                this.m_queryGrid.Columns[(int)Columns.Operator].Width); ;
        }

        private void OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                this.AllowSave();
            }
            catch(Exception) { }
        }
    }
}
